package com.ruoyi.inspection.domain.receiveVo;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.constant.GlobalConstants;
import com.ruoyi.common.enums.JobTypeInitEnum;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.inspection.config.JobBillTypeEnum;
import com.ruoyi.inspection.config.JobDepartmentEnum;
import com.ruoyi.inspection.config.JobStatusEnum;
import com.ruoyi.inspection.constant.InspectionConstant;
import com.ruoyi.inspection.controller.GovernJobPlanBillPush;
import com.ruoyi.system.domain.AppCreateJobBill;
import com.ruoyi.system.domain.JobPlanBillDeclare;
import com.ruoyi.system.domain.TemporaryStaffAccount;
import lombok.Data;

import java.io.Serializable;
import java.util.Date;
import java.util.UUID;

/**
 * 上报 特殊作业票证信息
 */
@Data
public class ReceiveJobTicket implements Serializable {
    //// 唯一编码，36 位uuid，必填
    private String id;
    private String jobId;
    //企业编码
    private String companyCode;
    //作业类型
    private String ticketType;
    // 签发时间，时间格式 yyyy-MM-dd HH:mm:ss
    private String issueTime;
    // 作业开始时间 yyyy-MM-dd HH:mm:ss
    private String startTime;
    // 结束时间 yyyy-MM-dd HH:mm:ss
    private String endTime;
    // 验收时间，时间格式 yyyy-MM-dd HH:mm:ss
    private String acceptanceTime;
    //作业地点
    private String ticketPosition;
    //作业内容
    private String ticketContent;
    //经度，必填，格式数字保留小数点后六位
    private String longitude;
    //纬度，必填，格式数字保留小数点后六位
    private String latitude;
    //作业状态，必填 0 未签发 1 已签发 3 已验收 4 作废 5 撤销
    private String ticketStatus;
    //安全监管人员姓名（监管人员姓名，通过英文逗号隔开）
    private String supervisorName;
    //施工人员 (通过英文逗号隔开)
    private String workerName;
    // 施工单位名称（施工单位名称，通过英文逗号隔开）
    private String workDepartment;
    // 施工人员编码：人员基础信息的人员id，多个通过英文逗号隔开
    private String personId;
    // 施工单位统一社会信用代码，当是承包商作业时，需上传，多个通过英文逗号隔开
    private String socialCreditCode;
    //是否承包商作业（0、否 1、是）
    private String isContractorWork;
    //作业负责
    private String ticketResponsName;
    ////负责人联系方式，
    private String majorPersonMobile;
    // 作业是否变更过 0 否 1 是
    private String isChanged;
    // 作业变更原因
    private String changedCause;
    // 作业是否取消 0 否 1 是，
    private String isCancelled;
    // 作业作废原因，
    private String cancelledCause;
    // 删除状态
    private String deleted;
    private String createBy;
    private String createDate;
    private String updateBy;
    private String updateDate;


    /**
     * 构建作业票对象
     * @param jobBill
     * @return
     */
    public static ReceiveJobTicket convertToReceiveJobTicket(AppCreateJobBill jobBill, JobPlanBillDeclare jobPlanBillDeclare) {
        String content = jobBill.getContent();
        String billNumber = jobBill.getPtw();
        if (StringUtils.isEmpty(content) || StringUtils.isEmpty(billNumber)) {
            return null;
        }


        JSONObject object = JSONObject.parse(content);
        // 查询作业票状态，非验收项目不上报， 0未签发 1已签发 3已验收 4作废 5撤销
        String ticketStatus = jobBillStatusHandler(object, jobBill.getJobType());
        // 作业票状态校验
        if (!JobStatusEnum.YYS.getCode().equals(ticketStatus)
                && !JobStatusEnum.ZF.getCode().equals(ticketStatus)
                && !JobStatusEnum.YQF.getCode().equals(ticketStatus)) {
            return null;
        }

        String acceptanceTime = jobAcceptanceTimeHandler(object, jobBill.getJobType());
        if (StringUtils.isEmpty(acceptanceTime)) { return null; }

        String governId = jobBill.getGovernId();
        governId = StringUtils.isEmpty(governId) ? UUID.randomUUID().toString() : governId;

        // 作业类型判断
        String jobType = jobBill.getJobType();
        if (StringUtils.isEmpty(jobType)) { return null; }
        String jobTypeDesc = JobTypeInitEnum.valueOfDesc(Integer.valueOf(jobType));
        if (StringUtils.isEmpty(jobTypeDesc)) { return null; }
        String jobType2 = JobBillTypeEnum.valueOfCode2(jobTypeDesc.substring(0, 2));
        if (StringUtils.isEmpty(jobType2)) { return null; }
        // 作业级别判断
        String zyjb = object.containsKey("zyjb") ? object.getString("zyjb") : "";
        if (StringUtils.isNotEmpty(zyjb))  {
            jobType2 = JobBillTypeEnum.valueOfCode(zyjb);
        }

        // 作业票起始、截至时间
        JSONArray dates = object.containsKey("jobDate") ? object.getJSONArray("jobDate") : null;
        if (StringUtils.isEmpty(dates) || dates.size()<2)  { return null; }
        String startTime = dates.get(0).toString();
        String endTime = dates.get(1).toString();
        startTime = startTime.length() < 19 ? startTime + ":00" : startTime;
        endTime = endTime.length() < 19 ? endTime + ":00" : endTime;
        // 作业地点
        String local = object.containsKey("local") ? object.getString("local") : "";
        // 作业内容
        String zynr = object.containsKey("zynr") ? object.getString("zynr") : "";
        // 作业负责人
        String zyfzr = object.containsKey("zyfzr") ? object.getString("zyfzr") : null;
        String zyfzr2 = jobPlanBillDeclare.getJobPersonCharge();
        zyfzr = StringUtils.isNotEmpty(zyfzr) ? zyfzr : zyfzr2;
        // 监护人
        String jhr = object.containsKey("jhr") ? StringUtils.join(object.getJSONArray("jhr"), ",") : null;
        jhr = StringUtils.isNotEmpty(jhr) ? jhr : StringUtils.isNotEmpty(zyfzr) ? zyfzr : "未指定";
        //作业人
        String zyr = "未指定";
        Object zyrObject = object.containsKey("zyr") ? object.get("zyr"):  null;
        if (zyrObject instanceof String) {
            zyr = (String) zyrObject;
        } else if (zyrObject instanceof String[]) {
            String[] zyrArray = (String[]) zyrObject;
            zyr = StringUtils.isNotEmpty(zyrArray) ? String.join(",", zyrArray) : zyr;
        }
        // 作业单位
        String zydw = object.containsKey("zydw") ? object.getString("zydw") : "";
        // 是否承包商作业
        String isContractorWork = jobPlanBillDeclare.getContractorJob();
        Date updateDate = jobBill.getModifyDate()==null ? jobBill.getCreatedDate() : jobBill.getModifyDate();
        String updateDateStr = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", updateDate);
        // 社会信用代码
        String department = jobPlanBillDeclare.getWorkShop();
        String socialCreditCode = JobDepartmentEnum.valueOfCode(department);


        ReceiveJobTicket jobVo = new ReceiveJobTicket();
        jobVo.setId(governId);
        jobVo.setIssueTime(startTime);
        jobVo.setJobId(jobPlanBillDeclare.getGovernId());
        jobVo.setCompanyCode(GlobalConstants.COMPANY_CODE);
        jobVo.setTicketType(jobType2);
        jobVo.setStartTime(startTime);
        jobVo.setEndTime(endTime);
        jobVo.setAcceptanceTime(acceptanceTime);
        jobVo.setTicketPosition(local);
        jobVo.setTicketContent(zynr);
        jobVo.setLongitude(InspectionConstant.LONGITUDE);
        jobVo.setLatitude(InspectionConstant.LATITUDE);
        jobVo.setTicketStatus(ticketStatus);
        jobVo.setSupervisorName(jhr);
        jobVo.setWorkerName(zyr);
        jobVo.setWorkDepartment(zydw);
        jobVo.setSocialCreditCode(socialCreditCode);
        jobVo.setIsContractorWork(isContractorWork);
        jobVo.setTicketResponsName(zyfzr);
        jobVo.setIsChanged("0");
        jobVo.setChangedCause("无");
        jobVo.setIsCancelled("0");
        jobVo.setCancelledCause("无");
        jobVo.setDeleted("0");
        jobVo.setCreateDate(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", jobBill.getCreatedDate()));
        jobVo.setCreateBy(StringUtils.isEmpty(jobBill.getCreatedBy()) ? "admin" : jobBill.getCreatedBy());
        jobVo.setUpdateDate(updateDateStr);
        jobVo.setUpdateBy(jobBill.getModifyBy()==null ? "admin" : jobBill.getModifyBy());

        jobBill.setTicketStatus(ticketStatus);
        jobBill.setGovernId(governId);
        return jobVo;
    }



    public static String jobBillStatusHandler(JSONObject object, String jobType) {
        String yjqm2 = object.containsKey("yjqm2") ? object.getString("yjqm2") : "";
        String yjqm3 = object.containsKey("yjqm3") ? object.getString("yjqm3") : "";
        String yjqm4 = object.containsKey("yjqm4") ? object.getString("yjqm4") : "";
        String yjqm5 = object.containsKey("yjqm5") ? object.getString("yjqm5") : "";
        String yjqm6 = object.containsKey("yjqm6") ? object.getString("yjqm6") : "";
        String yjqm7 = object.containsKey("yjqm7") ? object.getString("yjqm7") : "";

        String jobStatus = null;
        switch(jobType) {
            // 吊装安全作业票
            case "1" :
                jobStatus = StringUtils.isNotEmpty(yjqm5) ? JobStatusEnum.YYS.getCode()
                        : StringUtils.isNotEmpty(yjqm4) ? JobStatusEnum.YQF.getCode()
                        : JobStatusEnum.WQF.getCode();
                break;
            // 动火安全作业票
            case "2" :
                jobStatus = StringUtils.isNotEmpty(yjqm7) ? JobStatusEnum.YYS.getCode()
                        : StringUtils.isNotEmpty(yjqm6) ? JobStatusEnum.YQF.getCode()
                        : JobStatusEnum.WQF.getCode();
                break;
            // 高处安全作业票
            case "3" :
                jobStatus = StringUtils.isNotEmpty(yjqm5) ? JobStatusEnum.YYS.getCode()
                        : StringUtils.isNotEmpty(yjqm4) ? JobStatusEnum.YQF.getCode()
                        : JobStatusEnum.WQF.getCode();
                break;
            // 动土安全作业票
            case "4" :
                jobStatus = StringUtils.isNotEmpty(yjqm5) ? JobStatusEnum.YYS.getCode()
                        : StringUtils.isNotEmpty(yjqm4) ? JobStatusEnum.YQF.getCode()
                        : JobStatusEnum.WQF.getCode();
                break;
            // 临时用电安全作业票
            case "5" :
                jobStatus = StringUtils.isNotEmpty(yjqm5) ? JobStatusEnum.YYS.getCode()
                        : StringUtils.isNotEmpty(yjqm4) ? JobStatusEnum.YQF.getCode()
                        : JobStatusEnum.WQF.getCode();
                break;
            // 动用射线安全作业票
            case "6" :
                jobStatus = StringUtils.isNotEmpty(yjqm4) ? JobStatusEnum.YQF.getCode()
                        : JobStatusEnum.WQF.getCode();
                break;
            // 断路安全作业票
            case "7" :
                jobStatus = StringUtils.isNotEmpty(yjqm4) ? JobStatusEnum.YYS.getCode()
                        : StringUtils.isNotEmpty(yjqm3) ? JobStatusEnum.YQF.getCode()
                        : JobStatusEnum.WQF.getCode();
                break;
            // 盲板抽堵安全作业票
            case "8" :
                jobStatus = StringUtils.isNotEmpty(yjqm3) && StringUtils.isNotEmpty(yjqm4) ? JobStatusEnum.YYS.getCode()
                        : StringUtils.isNotEmpty(yjqm2) ? JobStatusEnum.YQF.getCode()
                        : JobStatusEnum.WQF.getCode();
                break;
            // 设备开孔安全作业票
            case "9" :
                jobStatus = StringUtils.isNotEmpty(yjqm4) ? JobStatusEnum.YQF.getCode()
                        : JobStatusEnum.WQF.getCode();
                break;
            // 受限空间安全作业票
            case "10" :
                jobStatus = StringUtils.isNotEmpty(yjqm5) ? JobStatusEnum.YYS.getCode()
                        : StringUtils.isNotEmpty(yjqm4) ? JobStatusEnum.YQF.getCode()
                        : JobStatusEnum.WQF.getCode();
                break;
            default: jobStatus = JobStatusEnum.WQF.getCode();
        }

        return jobStatus;
    }

    public static String jobAcceptanceTimeHandler(JSONObject object, String jobType) {
        String date2 = object.containsKey("qianmingDt2") ? object.getString("qianmingDt2") : "";
        String date3 = object.containsKey("qianmingDt3") ? object.getString("qianmingDt3") : "";
        String date4 = object.containsKey("qianmingDt4") ? object.getString("qianmingDt4") : "";
        String date5 = object.containsKey("qianmingDt5") ? object.getString("qianmingDt5") : "";
        String date6 = object.containsKey("qianmingDt6") ? object.getString("qianmingDt6") : "";
        String date7 = object.containsKey("qianmingDt7") ? object.getString("qianmingDt7") : "";

        String acceptanceTime = null;
        switch(jobType) {
            // 吊装安全作业票
            case "1" :
                acceptanceTime = date5;
                break;
            // 动火安全作业票
            case "2" :
                acceptanceTime = date7;
                break;
            // 高处安全作业票
            case "3" :
                acceptanceTime = date5;
                break;
            // 动土安全作业票
            case "4" :
                acceptanceTime = date5;
                break;
            // 临时用电安全作业票
            case "5" :
                acceptanceTime = date5;
                break;
            // 动用射线安全作业票
            case "6" :
                acceptanceTime = date4;
                break;
            // 断路安全作业票
            case "7" :
                acceptanceTime = date4;
                break;
            // 盲板抽堵安全作业票
            case "8" :
                acceptanceTime = date3;
                break;
            // 设备开孔安全作业票
            case "9" :
                acceptanceTime = date4;
                break;
            // 受限空间安全作业票
            case "10" :
                acceptanceTime = date5;
                break;
            default: acceptanceTime = null;
        }

        return acceptanceTime;
    }

}
